package com.qfedu.stussm.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    private String[] urls = new String[]{
            ".js", ".css", ".png", ".jpg", "login.html", "login.do", "code.do"
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String u = request.getRequestURI();
        boolean r = false;
        for (String url : urls) {
            if (u.endsWith(url)) {
                //放行
                r = true;
                break;
            }
        }
        if (r) {
            //不需要校验，放行
            chain.doFilter(request, response);
        } else {
            //校验是否登录
            if (request.getSession().getAttribute("user") == null) {
                //拦截,跳转到登录页面
                response.sendRedirect("/login.html");

            } else {
                //放行
                chain.doFilter(request, response);
            }
        }
    }

   /* @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取请求路径
        HttpServletRequest servletRequest=(HttpServletRequest)request;
        String url=servletRequest.getRequestURI();
        //2.验证是否需要拦截
        boolean r=false;
        for(String u:urls){
            if(url.endsWith(u)){
                //放行
                r=true;
                break;
            }
        }
        if(r){
            //不需要校验，放行
            chain.doFilter(request, response);
        }else {
            //校验是否登录
            if(servletRequest.getSession().getAttribute("user")==null){
                //拦截,跳转到登录页面
                HttpServletResponse servletResponse=(HttpServletResponse) response;
                servletResponse.sendRedirect("/login.html");

            }else {
                //放行
                chain.doFilter(request, response);
            }
        }
    }*/
}
